<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>参数列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- card部分 -->
        <el-card>
            <el-alert
                title="注意：只允许为第三级分类设置相关参数！"
                type="warning"
                show-icon
                :closable="false">
            </el-alert>
            <el-row class="selectCate">
                <span>选择商品分类：</span>  
                <!-- 级联选择器部分 -->
                <el-cascader
                    v-model="selectKeys"
                    :options="categoriesData"
                    :props="categoryParams"
                    @change="handleChange">
                </el-cascader>
            </el-row>
              <el-tabs v-model="activeName"  @tab-click="tabClick">
                <el-tab-pane label="动态参数" name="many">
                    <el-button 
                        type="primary" size="mini" 
                        :disabled="selectKeys.length>0?false:true"
                        @click="addParamsDialog">添加参数
                    </el-button>
                    <!-- table部分 -->
                    <el-table 
                        :data="dynamicParamsData" 
                        border
                        stripe>
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                 <el-tag
                                    :key="index"
                                    v-for="(tag,index) in scope.row.attr_vals"
                                    closable
                                    :disable-transitions="false"
                                    @close="handleClose(index,scope.row)">
                                    {{tag}}
                                </el-tag>
                                <el-input
                                    v-if="scope.row.inputVisible"
                                    v-model="scope.row.inputValue"
                                    ref="saveTagInput"
                                    @keyup.enter.native="handleInputConfirm(scope.row)"
                                    @blur="handleInputConfirm(scope.row)">
                                </el-input>
                                <el-button 
                                    v-else 
                                    class="button-new-tag" 
                                    size="small" 
                                    @click="showInput(scope.row)">+ New Tag
                                </el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index" label="#"></el-table-column>
                        <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                         <el-table-column label="操作">
                             <template slot-scope="scope">
                                <el-button type="primary" size="mini" icon="el-icon-edit" @click="editDynamic(scope.row)">编辑</el-button>
                                <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteDymamic(scope.row)">删除</el-button>
                             </template>
                         </el-table-column>
                    </el-table>
                </el-tab-pane>
                <el-tab-pane label="静态参数" name="only">
                    <el-button 
                        type="primary" size="mini" 
                        :disabled="selectKeys.length>0?false:true"
                        @click="addParamsDialog">添加参数</el-button>
                    <!-- table部分 -->
                    <el-table 
                        :data="dynamicParamsData" 
                        border
                        stripe>
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                 <el-tag
                                    :key="index"
                                    v-for="(tag,index) in scope.row.attr_vals"
                                    closable
                                    :disable-transitions="false"
                                    @close="handleClose(index,scope.row)">
                                    {{tag}}
                                </el-tag>
                                <el-input
                                    v-if="scope.row.inputVisible"
                                    v-model="scope.row.inputValue"
                                    ref="saveTagInput"
                                    @keyup.enter.native="handleInputConfirm(scope.row)"
                                    @blur="handleInputConfirm(scope.row)">
                                </el-input>
                                <el-button 
                                    v-else 
                                    class="button-new-tag" 
                                    size="small" 
                                    @click="showInput(scope.row)">+ New Tag
                                </el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index" label="#"></el-table-column>
                        <el-table-column label="属性名称" prop="attr_name"></el-table-column>
                         <el-table-column label="操作">
                             <template slot-scope="scope">
                                <el-button type="primary" size="mini" icon="el-icon-edit" @click="editDynamic(scope.row)">编辑</el-button>
                                <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteDymamic(scope.row)">删除</el-button>
                             </template>
                         </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-card>


        <!-- addparamsdialog部分 -->
        <el-dialog
            title="添加动态参数"
            :visible.sync="addParamsDialogVisible"
            >
            <el-form 
                ref="addParamsPialogFormRef" 
                :model="addParamsPialogForm" 
                :rules="addParamsPialogRules"
                label-width="80px">
                <el-form-item label="动态参数" prop="params">
                    <el-input v-model="addParamsPialogForm.params"></el-input>
                </el-form-item>
            </el-form>    
            <span slot="footer" class="dialog-footer">
                <el-button @click="addParamsDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitAddParamsDialog">确 定</el-button>
            </span>
        </el-dialog>

        <!-- edit dialog部分 -->
          <el-dialog
            title="修改动态参数"
            :visible.sync="editDialogVisible"
            >
            <el-form 
                ref="editdialogFormRef" 
                :model="editdialogForm" 
                :rules="editdialogRules"
                label-width="80px">
                <el-form-item label="动态参数" prop="params">
                    <el-input v-model="editdialogForm.params"></el-input>
                </el-form-item>
            </el-form>    
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="sumbitEditDialog">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data(){
        return{
            selectKeys:[],
            categoriesData:[],
            addParamsDialogVisible:false,
            categoryParams:{
                label:"cat_name",
                value:"cat_id",
                children:"children",
                expandTrigger: 'hover'
            },

            categoryId:"",

            attr_id:"",
            editDialogVisible:false,
            editdialogForm:{
               params:""
            },
            activeName:"many",
            dynamicParamsData:[],//参数数据

            addParamsPialogForm:{
               params:"" 
            },
            addParamsPialogRules:{
                params:[
                    { required: true, message: '此选项不能为空！', trigger: 'blur' },
                ]
            },
            editdialogRules:{
                 params:[
                    { required: true, message: '此选项不能为空！', trigger: 'blur' },
                ] 
            }
        }
    },
    created(){
        this.getCategoriesData();
    },  
    methods:{
        async getCategoriesData(){
            let {data:res} =await this.$axios.get("http://timemeetyou.com:8889/api/private/v1/categories")
            if(res.meta.status ===200){
                this.$message.success("获取商品分类数据成功！")
            }
            this.categoriesData = res.data;
        },
        handleChange(){
            if(this.selectKeys.length <3){
                this.selectKeys =[];
            }
            //设置分类id
            this.categoryId = this.selectKeys[2]
            this.getparamslist();
           
        },
        async getparamslist(){
            //获取动态或是静态数据
            let {data:res} =await this.$axios.get(`http://timemeetyou.com:8889/api/private/v1/categories/${this.categoryId}/attributes`,{
                params:{sel:this.activeName}
            })
            if(res.data !==null){
                res.data.forEach(item=>{

                    item.inputValue ="";
                    item.inputVisible=false;

                    if(item.attr_vals){
                        item.attr_vals =  item.attr_vals.split(" ")
                    }else{
                        item.attr_vals =[]
                        
                    }
                })

                this.dynamicParamsData = res.data
                console.log(res.data)
            }
            return;
          
        },
        tabClick(){
            //根据不同activename获取不同的数据
            this.getparamslist();   
        },
        addParamsDialog(){
            this.addParamsDialogVisible = true
        },
        submitAddParamsDialog(){
            this.$refs.addParamsPialogFormRef.validate(async valid=>{
                if(valid){
                    let {data:res} = await this.$axios.post(`http://timemeetyou.com:8889/api/private/v1/categories/${this.categoryId}/attributes`,{
                        attr_name:this.addParamsPialogForm.params,
                        attr_sel:this.activeName,
                    })
                    if(res.meta.status === 201){
                        this.$message.success("创建成功!")
                        //重新获取数据
                        this.getparamslist();
                        this.addParamsDialogVisible = false;
                    }
                }else{
                    console.log("error submit")
                }
            })
            
        },
        editDynamic(data){

            this.editDialogVisible = true;
            this.attr_id = data.attr_id;
            this.editdialogForm.params= data.attr_name;

        },
        async  sumbitEditDialog(){
            let {data:res} =await this.$axios.put(`http://timemeetyou.com:8889/api/private/v1/categories/${this.categoryId}/attributes/${this.attr_id}`,{
                attr_name:this.editdialogForm.params,
                attr_sel:this.activeName,
            })
            if(res.meta.status ===200){
                this.$message.success("更新成功!")
                this.editDialogVisible = false;
                this.getparamslist();
            }
        },
        async deleteDymamic(data){
            this.attr_id = data.attr_id;
            this.editdialogForm.params= data.attr_name;
            let result = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err=>err);
            if(result === "cancel"){
                this.$message("已取消删除!")
            }else if(result === "confirm"){
                let {data:res} = await this.$axios.delete(`http://timemeetyou.com:8889/api/private/v1/categories/${this.categoryId}/attributes/${this.attr_id}`)
                if(res.meta.status === 200){
                    this.$message.success("删除成功!")
                    this.getparamslist();
                }
            }
        },
        async handleClose(index,row){
            row.attr_vals.splice(index,1)
            // arr.splice(index,1)
            //发起网络请求
            let {data:res} =await this.$axios.put(`http://timemeetyou.com:8889/api/private/v1/categories/${this.categoryId}/attributes/${row.attr_id}`,{
                attr_name:row.attr_name,
                attr_sel:this.activeName,
                attr_vals:row.attr_vals.join(" ")
            })
        },
        async handleInputConfirm(row){
            if(row.inputValue.trim().length ===0){
                row.inputVisible = false;
                row.inputValue = "";
                return;
            }
            row.attr_vals.push(row.inputValue.trim())
            row.inputVisible = false;
            row.inputValue = "";
            //发起网络请求
            let {data:res} =await this.$axios.put(`http://timemeetyou.com:8889/api/private/v1/categories/${this.categoryId}/attributes/${row.attr_id}`,{
                attr_name:row.attr_name,
                attr_sel:this.activeName,
                attr_vals:row.attr_vals.join(" ")
            })

            if(res.meta.status ===200){
                this.$message.success("更新数据成功!")
            }
        },
        showInput(row){
            row.inputVisible = true;
            this.$nextTick(()=>{
                this.$refs.saveTagInput.$refs.input.focus();
            })
        }
    }

}
</script>
<style lang="less" scoped>
    .el-breadcrumb{
        margin-bottom: 15px;
    }
    .el-alert{
        margin-bottom: 15px;
    }
    .selectCate,.el-button{
        margin-bottom: 15px;
    }

    .el-tag + .el-tag {
    margin-left: 10px;
    }
    .button-new-tag {
        margin-left: 10px;
        height: 32px;
        line-height: 30px;
        padding-top: 0;
        padding-bottom: 0;
    }
    .input-new-tag {
        width: 90px;
        margin-left: 10px;
        vertical-align: bottom;
    }
    .el-input{
        margin-left: 10px;
        width: 120px;
    }
</style>